package smashedapples.google.financials
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	import mx.utils.ObjectUtil;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.google.consts.GoogleConsts;
	import smashedapples.google.vo.StockQuoteVO;

	public class GoogleStockTicker extends NonVisualComponent
	{	
		[Bindable] public var result:ArrayCollection = new ArrayCollection();
		
		public var timerDelay:Number = 1000;
		
		public var symbols:Array = [];
		
		public var timer:Timer;
		
		public function GoogleStockTicker():void
		{
			this.addEventListener( FlexEvent.CREATION_COMPLETE, handleCreationComplete );
		}
		
		protected function handleCreationComplete( event:FlexEvent ):void
		{
			setupTimer();
		}
		
		private function setupTimer( event:TimerEvent = null ):void
		{
			if( this.timer != null )
				this.timer.stop();
						
			this.timer = new Timer( this.timerDelay, 1 );
			this.timer.addEventListener( TimerEvent.TIMER_COMPLETE, setupTimer );
			this.timer.start();
			
			this.getQuotes();
		}
	
		public function getQuotes():void
		{
			
			if( this.symbols.length == 0 )
				return;
			
			var service:HTTPService = new HTTPService();
				service.url = GoogleConsts.FINANCIALS_STOCK_QUOTE_URL( this.symbols );
				service.resultFormat = "object";
				service.addEventListener(ResultEvent.RESULT, handleGetQuotesResult );
				service.addEventListener(FaultEvent.FAULT, handleGetQuotesFault);
				service.send();
		}
		
		
		protected function handleGetQuotesResult( event:ResultEvent ):void
		{

			var string:String = String( event.result );
				string = string.slice( 4 );			
			var obj:Object = JSON.decode( string );
			
			var  array:Array = [];
			for each( var item:Object in obj)
			{
				array.push( new StockQuoteVO( item ) );
			} 
			
			//trace( ObjectUtil.toString( array ));
			
			this.result = new ArrayCollection( array );
			
			
		}
		
		protected function handleGetQuotesFault( event:FaultEvent ):void
		{
			trace(event.fault);
		}
		
		
		
		
	}
}